package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.feign.dto.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Override
    public void upDown(Long id, Integer status) {
        if (id == null || status == null) {
            throw new RuntimeException("参数异常");
        }
        this.update(Wrappers.lambdaUpdate(Item.class)
                .set(Item::getStatus, status)
                .set(Item::getUpdateTime, new Date())
                .eq(Item::getId, id));
    }

    @Override
    public void delItem(Long id) {
        Item item = this.getById(id);
        if (item.getStatus() == 1) {
            throw new RuntimeException("上架的商品不能编辑，请先下架！");
        }
        this.removeById(id);
    }

    @Override
    public void editItem(Item item) {

        checkParam(item);//校验参数

        Item dbItem = this.getById(item.getId());

        if (dbItem.getStatus() == 1) {
            throw new RuntimeException("上架的商品不能编辑，请先下架！");
        }


        item.setId(item.getId());
        item.setSold(dbItem.getSold());
        item.setCommentCount(item.getCommentCount());
        item.setCreateTime(item.getCreateTime());
        item.setUpdateTime(new Date());
        this.updateById(item);

    }

    @Override
    public void reduceItemStockNum(Long itemId, Integer num) {
        Item item = getById(itemId);
        item.setStock(item.getStock() - num);
        updateById(item);
    }

    @Override
    public void returnItemStockNum(Long itemId, Integer num) {
        Item item = this.getById(itemId);
        item.setStock(item.getStock() + num);
        this.updateById(item);
    }

    public void checkParam(Item item) {
        if (item == null || StringUtils.isBlank(item.getName()) || StringUtils.isBlank(item.getCategory())
                || StringUtils.isBlank(item.getBrand()) || item.getPrice() == null || item.getStock() == null
                || item.getStock() <= 0 || StringUtils.isBlank(item.getSpec()) || StringUtils.isBlank(item.getImage())
                || item.getIsAD() == null) {
            throw new RuntimeException("参数异常");
        }
    }

}
